package cn.txun.csmall.passport.security;

import cn.txun.csmall.passport.mapper.AdminMapper;
import cn.txun.csmall.passport.pojo.vo.AdminLoginInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 实现UserDetailsService接口
 *
 * @author java@txun.cn
 * @version 0.0.1
 */

@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private AdminMapper adminMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.debug("Spring Security自动调用UserDetailsServiceImpl.loadUserByUsername,用户名：{}",username);
        //根据用户名从数据库中查询匹配的用户信息
        AdminLoginInfoVO loginInfo = adminMapper.getLoginInfoByUsername(username);

        if(loginInfo==null){
            log.debug("此用户名没有匹配的用户详情，将返回null");
            return null;
        }
        log.debug("用户名匹配成功！准备返回此用户匹配的UserDetails类型的对象");

        //使用自定义AdminDetails封装用户信息
        Collection<GrantedAuthority> authorities =new ArrayList<>();
        List<String> permissions = loginInfo.getPermissions();
        for(String permission:permissions){
            GrantedAuthority authority = new SimpleGrantedAuthority(permission);
            authorities.add(authority);
        }

        AdminDetails adminDetails = new AdminDetails(
                loginInfo.getId(),loginInfo.getUsername(),
                loginInfo.getPassword(),loginInfo.getEnable()==1,
                authorities
        );
                 /* = User.builder()//开启构建
               .username(loginInfo.getUsername())
                .password(loginInfo.getPassword())
                .disabled(loginInfo.getEnable()==0)     //账号状态是否禁用
                .accountLocked(false)//账号状态是否锁定
                .accountExpired(false)//账号状态是否过期
                .authorities("这是一个临时用的山寨权限")
                .build();//构建完成*/
        log.debug("即将向Spring Security返回UserDetails类型的对象，{}",adminDetails);
        return adminDetails;//千万不忘记返回
    }
}
